var pathRequestUrl;
var partnerPriceRecord;
var partnerPriceObj;
var gridPartner;
var row_current = -1;
var col_current = -1;

Ext.onReady(function(){
	Ext.QuickTips.init();
    pathRequestUrl = 'ListPartnerPricesData.php';
    
	function isEmpty(obj){
		if (typeof obj == 'undefined' || obj === null || obj === '') 
			return true;
		if (typeof obj == 'number' && isNaN(obj)) 
			return true;
		if (obj instanceof Date && isNaN(Number(obj))) 
			return true;
		return false;
	};

	var formatDate = function(value){
		if (isEmpty(value)) 
			return '';
		try {
			return value ? ((value.dateFormat('d/m/Y') != '01/01/1970') ? value.dateFormat('d/m/Y') : '') : '';
		} 
		catch (e) {
			console.debug(e);
		}
	};
	//--------------------------	
	Ext.ns('Extensive.grid');
	Extensive.grid.ItemDeleter = Ext.extend(Ext.grid.RowSelectionModel, {
		width: 30,		
		sortable: false,
		dataIndex: 0, // this is needed, otherwise there will be an error		
		menuDisabled: true,
		fixed: true,
		id: 'deleter',		
		initEvents: function(){
			Extensive.grid.ItemDeleter.superclass.initEvents.call(this);
			this.grid.on('cellclick', function(grid, rowIndex, columnIndex, e){
				if (columnIndex == grid.getColumnModel().getIndexById('deleter')) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (record.data.id == 0) 
                        return false;
                    Ext.Msg.show({
                        title: 'Xác nhận',
                        buttons: Ext.MessageBox.YESNO,
                        icon: Ext.MessageBox.QUESTION,
                        msg: "Bạn có chắc là muốn xóa không ?",
                        fn: function(btn){
                            if (btn == 'yes') {
                                deletePartner(record);
                            }
                        }
                    });
                }
			});
		},		
		renderer: function(v, p, record, rowIndex){
			return '<div class="extensive-remove" style="width: 15px; height: 16px;"></div>';
		}
	});	
	var itemDeleter = new Extensive.grid.ItemDeleter();
	
	//-----------------------------
    partnerPriceRecord = [
	{name: 'id', type: 'string'},
        {name: 'partner_id', type: 'string'},
	{name: 'price', type: 'string'},
	{name: 'note', type: 'string'}
	];
    
    partnerPriceObj = Ext.data.Record.create(partnerPriceRecord);
    
    var partner = {
        add: function(){
    		addNewPartner(storePartnerPrices.getCount(), 2, true);
			//bbarPartner.moveLast();
        },
        remove: function(){          	     	
        },        
        find: function(){  
			gridPartner.getStore().load();
        },
		print: function(){
		}
    };
    
    //Doi tac:----------------------------------------   
    var storePartnerList = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            id: 'partner_id',
            fields: ['partner_id', 'partner_number', 'partner_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storePartnerList.on('beforeload', function(store){
        store.baseParams.action = 'getListPartner';
    });
    
    var render_partner_type = function(val){
        try {
            if (isEmpty(val) || (val == 0)) {
                return '';
            }
            
            var partnerObj = storePartnerList.queryBy(function(rec){
                return rec.data.partner_id == val;
            }).itemAt(0);
            if (partnerObj) 
                return partnerObj.data.partner_name;
            return '';
        } 
        catch (e) {
        }
    };
    
    var storePartnerPrices = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            id: 'id'
        }, partnerPriceObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
        
    storePartnerPrices.on('beforeload', function(){
        storePartnerPrices.baseParams.action = 'get';    
    });
            
	var tbarpartner = new Ext.Panel({
		items:[{
				xtype: 'toolbar',
				id: 'tbar2',
				items:[{
					text: 'Thêm',
					id: 'add_partner',
					cls: 'x-btn-text-icon',
					icon: 'images/icons/add.png',
					handler: partner.add
				}]
			}]
	});
	            
    var cmPartner = new Ext.grid.ColumnModel({
        defaults: {
            sortable: true
        },
        columns: [new Ext.grid.RowNumberer(), itemDeleter ,
		  {
            header: 'Đối Tác',
            dataIndex: 'partner_id',
            width: 120,
            renderer: render_partner_type,
            editor: new Ext.form.ComboBox({
                typeAhead: true,
                store: storePartnerList,
                valueField: 'partner_id',
                displayField: 'partner_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 150,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: false,
                listeners: {
                    select: function(combo, record, index){
                        gridPartner.startEditing(row_current, col_current);
                    }
                }
            })
        }, {
            header: 'Giá',
            dataIndex: 'price',
		width: 200,
		editor: new Ext.form.TextField( {
			allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
			})
        },
	{
            header: 'Mô tả',
            dataIndex: 'note',
		width: 200,
		editor: new Ext.form.TextField( {
			allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
			})
        }
	
	
	]
    });
	gridPartner = new Ext.grid.EditorGridPanel({
    	title: '',
        id: 'gridPartner',
        store: storePartnerPrices,
        cm: cmPartner,
        tbar: tbarpartner,
        stripeRows: true,
        height: 530,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
		selModel: itemDeleter,
		viewConfig: {
            forceFit: true,
            deferEmptyText: true,
            emptyText: 'No records found'
        },
        //autoHeight: true,
        listeners: {
	    	beforeedit: function(e){
                row_current = e.row;
                col_current = e.column;
            },
            afteredit: function(e){
                if (0 == e.record.data.id) {
                    insertPartner(e);
                }
                else {
                    updatePartner(e);
                }
            }         
        }    
    });
    
    var partnerFormPanel = new Ext.FormPanel({
        id: 'list_partner_panel',
        iconCls: 'form-icon',
        title: 'QL Thông Tin Giá Đối Tác',
        frame: true,
        width: 600,
        renderTo: 'list_partner_prices',
        items: [gridPartner]
    });          

});

/**
 * Functions --------------------------------------------------------------------------------------
 */
var addNewPartner = function(row_insert, col_edit, has_edit){
	var newRecord = new partnerPriceObj({
	id: 0,
        partner_id: 0,
        price: 0
    });
        
    gridPartner.getStore().insert(row_insert, newRecord);
    gridPartner.getView().refresh();
    if (has_edit) gridPartner.startEditing(row_insert, col_edit);
};

/**
 * Insert an partner
 * @author huudatxm
 */
var insertPartner = function(e){
    if (!checkDataInsert(e)) 
        return;
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
			e.record.reject();
            		alert('Giá của Đối Tác đã tồn tại. Vui lòng chọn lại!.');
            		return;
            	}
		if (result.data.id == null) {
			e.record.reject();
			alert('Nhập dữ liệu không hợp lệ!');
			return;
		}
                e.record.data.id = result.data.id;
                e.record.commit();
            	/**
                addNewPartner(gridPartner.getStore().getCount(), 3, false);
                gridPartner.startEditing(row_current, col_current);*/
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'insert',
            partner_id: e.record.data.partner_id,
            price: e.record.data.price
        }
    });
};

/**
 * Check data for insert
 * @author huudatxm
 */
var checkDataInsert = function(e){
    var data = e.record.data;
    return !(isEmpty(data.partner_id) ||
	     isEmpty(data.price) || (data.price == 0));
};

/**
 * Update
 * @author huudatxm
 */
var updatePartner = function(e){
	if(!checkDataInsert(e)) return;
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
			e.record.reject();
			gridPartner.getView().refresh();
            		alert('Giá của đối tác này đã tồn tại. Vui lòng chọn lại!.');
            		return;
            	}
                e.record.commit();
		gridPartner.getView().refresh();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'update',
            field: e.field,
            value: e.value,
            id: e.record.data.id
        }
    });
};

/**
 * Key Control
 * @author datnh
 */
var keyCustom = function(e){
    /*if (e.keyCode == 40) {
        //KeyDown	
        var store_size = gridPartner.getStore().getCount();
        if ((store_size - 1) == row_current) {
            if (0 == gridPartner.getStore().getAt(store_size - 1).data.partner_id) 
                return false;
            addNewPartner(store_size, 2, false);
        }
        row_current++;
        gridPartner.startEditing(row_current, col_current);
        gridPartner.getSelectionModel().selectRow(row_current);
    }
    else 
        if (e.keyCode == 38) {
            //KeyUp
            if (row_current > 0) {
                row_current--;
                gridPartner.startEditing(row_current, col_current);
                gridPartner.getSelectionModel().selectRow(row_current);
            }
        }*/
};

/**
 * Delete
 * @author huudatxm
 */
var deletePartner = function(record){
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                gridPartner.getStore().remove(record);
                gridPartner.getView().refresh();
            }
            else {
                alert('Không thể xóa vì lỗi phát sinh.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'delete',
	    id: record.data.id
        }
    });
};

